//
//  DetailViewController.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/20.
//

import UIKit

class DetailViewController: RViewController {

    /// 历史数据
    var historyData = [RModel]()
    var timeStamp = String()
    
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var contentViewHeight: NSLayoutConstraint!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableViewHeight: NSLayoutConstraint!
    var noteList = [String]()
    var cellHeight = [CGFloat]()
    // 距顶部距离
    @IBOutlet weak var marginTop: NSLayoutConstraint!
    @IBOutlet weak var headerBgHeight: NSLayoutConstraint!
    // 顶部五个小渐变条
    @IBOutlet weak var gradientView1: UIView!
    @IBOutlet weak var gradientView2: UIView!
    @IBOutlet weak var gradientView3: UIView!
    @IBOutlet weak var gradientView4: UIView!
    @IBOutlet weak var gradientView5: UIView!
    // 顶部五个label文字
    @IBOutlet weak var recordingTime: UILabel!
    @IBOutlet weak var less90SpO2: UILabel!
    @IBOutlet weak var averageSpO2: UILabel!
    @IBOutlet weak var lowestSpO2: UILabel!
    @IBOutlet weak var averagePR: UILabel!
    
    @IBOutlet weak var SpO2BgView: UIView!
    var SpO2ChartView = LineChartView()
    @IBOutlet weak var PulseRateBgView: UIView!
    var PRChartView = LineChartView()
    @IBOutlet weak var MontionView: UIView!
    var MotionChartView = LineChartView()
    /// 只有第一次才设置折线图弹框的代理，不然设置多次会崩溃
    var shouldSetClickedDelegate = 0
    
    /// 笔记是否展开
    var noteIsOpen = false
    /// 指示线
    var chartLineView = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.historyData = (CacheManager.manager.getValueForKey(self.timeStamp) as! [RModel])
        self.initBaseView()
        self.calculateTableViewHeight()
        self.initChartView()
        self.analysisData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    func initBaseView() {
        /// 刘海屏
        self.marginTop.constant = getStatusBarHight() + 11
        self.headerBgHeight.constant = getStatusBarHight() + 168
        self.scrollView.contentInsetAdjustmentBehavior = .never
        self.contentView.backgroundColor = hexColor("F9F9F9")
        self.scrollView.backgroundColor = hexColor("F9F9F9")
        self.view.backgroundColor = hexColor("F9F9F9")
        self.tableView.tableHeaderView = self.tableHeaderView()
        
        /// 添加渐变色
        self.addSubLayer(view: self.gradientView1, startColor: "83DFA3", endColor: "58C882")
        self.addSubLayer(view: self.gradientView2, startColor: "FFE59A", endColor: "FFC01E")
        self.addSubLayer(view: self.gradientView3, startColor: "FBBFFA", endColor: "D847DC")
        self.addSubLayer(view: self.gradientView4, startColor: "F997B6", endColor: "F05E7F")
        self.addSubLayer(view: self.gradientView5, startColor: "CDB2F4", endColor: "A686F4")
        
    }
    
    /// 添加渐变色
    func addSubLayer(view: UIView, startColor: String, endColor: String) {
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [hexColor(startColor)!.cgColor, hexColor(endColor)!.cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = view.bounds
        bgLayer1.startPoint = CGPoint(x: 0.07, y: 0)
        bgLayer1.endPoint = CGPoint(x: 1.1, y: 1.1)
        view.layer.insertSublayer(bgLayer1, at: 0)
    }
    
    /// 计算tableView高度
    func calculateTableViewHeight() {
        self.cellHeight.removeAll()
        self.noteList.removeAll()
        guard let notes = self.historyData.first?.notes else {
            self.tableViewHeight.constant = 0
            self.tableView.reloadData()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
                // 更新scrollView高度
                self.contentViewHeight.constant = self.MontionView.bottom + 20
            }
            return
        }
        self.noteList = notes
        
        var height:CGFloat = self.tableHeaderView().height
        
        if self.noteIsOpen == true {
            // 展开
            for str in notes {
                let needHeight = calculateLableSizeString(textStr: str, size: CGSize(width: kScreenWidth - 30, height: 100), font: regularFont(size: 13)!).height + 30
                self.cellHeight.append(needHeight)
                height += needHeight
            }
        }else {
            // 收起
            let needHeight = calculateLableSizeString(textStr: notes.first!, size: CGSize(width: kScreenWidth - 30, height: 100), font: regularFont(size: 13)!).height + 30
            self.cellHeight.append(needHeight)
            height += needHeight
        }
        
        if notes.count > 1 {
            self.tableView.tableFooterView = self.tableFooterView()
            height += self.tableFooterView().height
        }
        
        // 刷新tableView
        self.tableViewHeight.constant = height
        self.tableView.reloadData()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
            // 更新scrollView高度
            self.contentViewHeight.constant = self.MontionView.bottom + 20
        }
    }
    
    func tableHeaderView() -> UIView {
        let head = UIView.init(frame: CGRect(x: 0, y: 0, width: self.tableView.width, height: 24))
        let imageView = UIImageView.init(frame: CGRect(x: 14, y: 4, width: 20, height: 20))
        let image = UIImage.init(named: "detail6")
        imageView.contentMode = .scaleAspectFill
        imageView.image = image
        head.addSubview(imageView)
        return head
    }
    
    func tableFooterView() -> UIView {
        let foot = UIView.init(frame: CGRect(x: 0, y: 0, width: self.tableView.width, height: 24))
        let image = UIImageView.init(image: UIImage.init(named: self.noteIsOpen ? "detail8" : "detail7"))
        foot.addSubview(image)
        image.center = foot.center
        foot.isUserInteractionEnabled = true
        let ges = UITapGestureRecognizer.init(target: self, action: #selector(refreshTableViewOpenState))
        foot.addGestureRecognizer(ges)
        return foot
    }
    
    /// 展开或收起tableView
    @objc func refreshTableViewOpenState() {
        self.noteIsOpen = !self.noteIsOpen
        self.calculateTableViewHeight()
    }
    
    func initChartView() {
        
        let width = kScreenWidth - 30
        
        // 血氧
        self.SpO2ChartView = DetailChartViewTool.initDetailChartView(data: self.historyData, isSpO2: true)
        self.SpO2ChartView.frame = CGRect(x: 0, y: 30, width: width, height: self.SpO2BgView.height - 30)
        self.SpO2ChartView.delegate = self
        self.SpO2BgView.addSubview(self.SpO2ChartView)
        
        // 脉搏
        self.PRChartView = DetailChartViewTool.initDetailChartView(data: self.historyData, isSpO2: false)
        self.PRChartView.frame = CGRect(x: 0, y: 30, width: width, height: self.PulseRateBgView.height - 30)
        self.PRChartView.delegate = self
        self.PulseRateBgView.addSubview(self.PRChartView)
        
        // 运动
        self.MotionChartView = DetailChartViewTool.initMotionChartView(data: self.historyData)
        self.MotionChartView.frame = CGRect(x: 0, y: 30, width: width, height: self.MontionView.height - 30)
        self.MotionChartView.delegate = self
        self.MontionView.addSubview(self.MotionChartView)
        
        // 指示线
        self.chartLineView = UIView.init(frame: CGRect(origin: .zero, size: CGSize.init(width: 0.5, height: self.SpO2BgView.height + self.PulseRateBgView.height + self.MontionView.height - 30)))
        self.chartLineView.backgroundColor = hexColor("3468E2")! //十字线颜色
        self.scrollView.addSubview(self.chartLineView)
        self.scrollView.bringSubviewToFront(self.chartLineView)
        self.chartLineView.isHidden = true
    }
    
    @IBAction func shareBtnDidClicked(_ sender: Any) {
        guard let view = Bundle.main.loadNibNamed("ShareAlert", owner: nil, options: nil)?.first as? ShareAlert else {
            print("通过Xib加载失败")
            return
        }
        var passData = [[String: Any]]()
        for obj in historyData {
            passData.append(obj.toDictionary())
        }
        view.passData = passData
        view.timeStamp = self.timeStamp
        view.historyData = historyData
        view.frame = UIScreen.main.bounds
        self.view.addSubview(view)
    }
    
    /// 帮助
    @IBAction func questionBtnDidClicked(_ sender: Any) {
        let vc = SimpleWebViewController.init()
        vc.url = "https://checkmering.jp/app_help"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    /// 记笔记
    @IBAction func noteBtnDidClicked(_ sender: Any) {
        guard let view = Bundle.main.loadNibNamed("NoteAlert", owner: nil, options: nil)?.first as? NoteAlert else {
            print("通过Xib加载失败")
            return
        }
        view.frame = UIScreen.main.bounds
        self.view.addSubview(view)
        
        view.backText = { text in
            /// 存储到本地
            if var notes = self.historyData.first?.notes {
                notes.insert(text, at: 0)
                self.historyData.first?.notes = notes
            }else {
                var notes = [String]()
                notes.append(text)
                self.historyData.first?.notes = notes
            }
            CacheManager.manager.setValueForKey(self.timeStamp, self.historyData as NSCoding)
            self.calculateTableViewHeight()
        }
    }
    
    @IBAction func backBtnDidClicked(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    /// 分析值
    func analysisData() {
        
        if self.historyData.isEmpty {
            return
        }
        
        /// 记录时长
        let time = abs(Int(self.historyData.first!.timeStamp) - Int(self.historyData.last!.timeStamp)) + ReadRate
        self.recordingTime.text = FormatDate(second: time)
        
        // 低于90%时长、平均血氧、最低血氧、平均脉率
        var less90 = 0, totalSpO2 = 0, minSpO2 = 100, totalHR = 0
        for obj in self.historyData {
            if obj.spo2 < 90 {
                less90 += ReadRate
            }
            totalSpO2 += obj.spo2
            minSpO2 = min(minSpO2, obj.spo2)
            totalHR += obj.hr
        }
        self.less90SpO2.text = FormatDate(second: less90)
        self.averageSpO2.text = String(totalSpO2 / self.historyData.count)
        self.lowestSpO2.text = String(minSpO2)
        self.averagePR.text = String(totalHR / self.historyData.count)
        
        // 标题
        self.titleLabel.text = formatTimeStamp(time: self.historyData.first!.timeStamp, format: "MMM dd")
    }
    
}

extension DetailViewController: ChartViewDelegate {
    
    // 选中
    func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        
        self.chartLineView.isHidden = false
        self.chartLineView.frame.origin = CGPoint.init(x: highlight.xPx + self.SpO2BgView.left, y: self.SpO2BgView.top + 30)
        
        let obj = self.historyData[Int(entry.x)]
        let delegate = shouldSetClickedDelegate == 0 ? true : false
        shouldSetClickedDelegate += 1
        // 显示MarkerView标签
        if chartView == self.SpO2ChartView {
            self.PRChartView.highlightValue(highlight, callDelegate: delegate)
            self.MotionChartView.highlightValue(highlight, callDelegate: delegate)
        }
        if chartView == self.PRChartView {
            self.SpO2ChartView.highlightValue(highlight, callDelegate: delegate)
            self.MotionChartView.highlightValue(highlight, callDelegate: delegate)
        }
        if chartView == self.MotionChartView {
            self.SpO2ChartView.highlightValue(highlight, callDelegate: delegate)
            self.PRChartView.highlightValue(highlight, callDelegate: delegate)
        }
        
        // 时间
        let time = formatTimeStamp(time: obj.timeStamp, format: "HH:mm:ss")
        self.SpO2ChartView.marker = MarkerBaseView.configView(chartView: self.SpO2ChartView, title: time, value: String(obj.spo2))
        self.PRChartView.marker = MarkerBaseView.configView(chartView: self.PRChartView, title: time, value: String(obj.hr))
        self.MotionChartView.marker = MarkerBaseView.configView(chartView: self.MotionChartView, title: time, value: String(obj.vector))
    }
    
    // 取消选中
    func chartValueNothingSelected(_ chartView: ChartViewBase) {
        self.chartLineView.isHidden = true
        if chartView == self.SpO2ChartView {
            self.PRChartView.highlightValue(nil)
            self.MotionChartView.highlightValue(nil)
        }
        if chartView == self.PRChartView {
            self.SpO2ChartView.highlightValue(nil)
            self.MotionChartView.highlightValue(nil)
        }
        if chartView == self.MotionChartView {
            self.SpO2ChartView.highlightValue(nil)
            self.PRChartView.highlightValue(nil)
        }
    }
    
    // 缩放
    func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) {
        self.refreshChartView(chartView: chartView)
    }
    
    // 滑动
    func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) {
        self.refreshChartView(chartView: chartView)
    }
    
    func refreshChartView(chartView: ChartViewBase) {
        self.chartLineView.isHidden = true
        self.SpO2ChartView.highlightValue(nil)
        self.PRChartView.highlightValue(nil)
        self.MotionChartView.highlightValue(nil)
        let srcMatrix = chartView.viewPortHandler.touchMatrix
        
        if chartView == self.SpO2ChartView {
            self.PRChartView.viewPortHandler.refresh(newMatrix: srcMatrix, chart: self.PRChartView, invalidate: true)
            self.MotionChartView.viewPortHandler.refresh(newMatrix: srcMatrix, chart: self.MotionChartView, invalidate: true)
        }
        if chartView == self.PRChartView {
            self.SpO2ChartView.viewPortHandler.refresh(newMatrix: srcMatrix, chart: self.SpO2ChartView, invalidate: true)
            self.MotionChartView.viewPortHandler.refresh(newMatrix: srcMatrix, chart: self.MotionChartView, invalidate: true)
        }
        if chartView == self.MotionChartView {
            self.PRChartView.viewPortHandler.refresh(newMatrix: srcMatrix, chart: self.PRChartView, invalidate: true)
            self.SpO2ChartView.viewPortHandler.refresh(newMatrix: srcMatrix, chart: self.SpO2ChartView, invalidate: true)
        }
    }
    
}

extension DetailViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.cellHeight.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DetailTableViewCell") as! DetailTableViewCell
        cell.selectionStyle = .none
        cell.contentLabel.text = self.noteList[indexPath.row]
        cell.separLine.isHidden = indexPath.row == self.cellHeight.count - 1
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return self.cellHeight[indexPath.row]
    }
}
